Page({
  data: {
    notifications: []
  },

  onLoad() {
    this.getNotifications();
  },

  onShow() {
    this.getNotifications();
  },

    // 获取活动通知列表
    getNotifications() {
      const app = getApp();
      wx.request({
        url: app.globalData.onlineService + '/api/message/message',
        method: 'GET',
        data: {
          type: 'activity',  // 指定获取活动类型的消息
          page: 1,
          page_size: 20
        },
        header: {
          'Authorization': `Bearer ${app.globalData.userInfo.token}`
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.setData({
              notifications: res.data.data
            });
            // 将获取到的未读消息标记为已读
            const unreadMessageIds = res.data.data
            .filter(msg => msg.status === 0)
            .map(msg => msg.id);

            if (unreadMessageIds.length > 0) {
              wx.request({
                url: app.globalData.onlineService + '/api/message/message',
                method: 'POST',
                data: {
                  message_ids: unreadMessageIds
                },
                header: {
                  'Authorization': `Bearer ${app.globalData.userInfo.token}`
                },
                success: (res) => {
                  if (res.data.code === 200) {
                    console.log('消息状态更新成功');
                  }
                },
                fail: (err) => {
                  console.error('更新消息状态失败', err);
                }
              });
            } 

          }
        },
        fail: (err) => {
          console.error('获取活动通知失败', err);
          wx.showToast({
            title: '获取通知失败',
            icon: 'none'
          });
        }
      });
    },
  

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});